﻿using Dotnet6.Web.Common;
using Dotnet6.Web.DbEntitys;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Dotnet6.Web.Controllers
{
    public class UserController : WebBaseController
    {
        private readonly EFDbContext _dbContext;

        public UserController(EFDbContext dbContext, IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _dbContext = dbContext;//构造函数依赖注入 数据库上下文
        }

        /// <summary>
        /// 列表页
        /// </summary>
        public async Task<IActionResult> Index()
        {
            List<UserInfo> users = await GetUserListAsync();
            return View(users);//返回视图页面, 这里的users   在页面 @model 指定类型，就可以使用
        }

        /// <summary>
        /// 详情/编辑页面
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Edit(string id)
        {
            UserInfo? user = (await GetUserAsync(id)) ?? new UserInfo();
            return View(user);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(UserInfo user)
        {
            if (string.IsNullOrWhiteSpace(user.Id))
                await AddUserAsync(user);
            else
                await UpdateUserAsync(user);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public async Task<IActionResult> DeleteUserAsync(string id)
        {
            UserInfo? dbUser = await GetUserAsync(id);
            if (dbUser == null)
                throw new Exception("用户不存在！");
            _dbContext.UserInfos.Remove(dbUser);
            await _dbContext.SaveChangesAsync();
            return RedirectToAction("Index");
        }


        public async Task<List<UserInfo>> GetUserListAsync()
        {
            //AsNoTracking 不跟踪实体，查询更快
            var list = await _dbContext.UserInfos.AsNoTracking().ToListAsync();
            return list;
        }

        public async Task AddUserAsync(UserInfo user)
        {
            user.Check();
            if (await _dbContext.UserInfos.AnyAsync(x => x.Account == user.Account))
                throw new Exception("该账号已注册，请更换后重试！");
            user.Id = Guid.NewGuid().ToString("N");
            user.CreateTime = DateTime.Now;
            _dbContext.UserInfos.Add(user);//跟踪状态 实体状态更改
            await _dbContext.SaveChangesAsync();//执行状态更改，操作数据库
        }

        public Task<UserInfo?> GetUserAsync(string id)
        {
            return _dbContext.UserInfos.FirstOrDefaultAsync(x => x.Id == id);
        }

        public async Task UpdateUserAsync(UserInfo user)
        {
            UserInfo? dbUser = await GetUserAsync(user.Id);
            if (dbUser == null)
                throw new Exception("用户不存在！");
            if (await _dbContext.UserInfos.AnyAsync(x => x.Account == user.Account && x.Id != user.Id))
                throw new Exception("该账号已注册，请更换后重试！");
            dbUser.Edit(user.Name, user.Account, user.Password, user.Age, user.Phone);
            await _dbContext.SaveChangesAsync();
        }

    }
}
